package bspay

import (
	"context"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bspay/bspay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Bspay{
		SecretKey:  config.SecretKey,
		Url:        config.Url,
		ReturnUrl:  config.ReturnUrl,
		NotifyUrl:  config.NotifyUrl,
		PrivateKey: config.PrivateKey,
	}
}

type Bspay struct {
	SecretKey  string
	Url        string
	ReturnUrl  string
	NotifyUrl  string
	MerchantId string
	PrivateKey string
}

// 代付订单创建
func (Bs *Bspay) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	// 请求第三方接口
	appKey := Bs.PrivateKey
	amount := fmt.Sprintf("%.2f", req["Order"].(map[string]any)["RealAmount"])
	orderId := req["Order"].(map[string]any)["OrderNo"].(string)
	url := Bs.Url + "/api/withdraw"
	bankCode := ""
	receiveName := ""
	receiveAccount := ""
	fmt.Println(req["Order"].(map[string]any)["UserBank"].(map[string]any)["BankCode"].(string))
	if _, exists := req["Order"].(map[string]any)["UserBank"]; exists {
		bankCode = req["Order"].(map[string]any)["UserBank"].(map[string]any)["BankCode"].(string)
		receiveName = req["Order"].(map[string]any)["UserBank"].(map[string]any)["UserName"].(string)
		receiveAccount = req["Order"].(map[string]any)["UserBank"].(map[string]any)["CardNumber"].(string)
	}
	draw, err := bspay.Withdraw(url, appKey, amount, orderId, receiveAccount, receiveName, bankCode, Bs.NotifyUrl, Bs.SecretKey)
	if err != nil {
		return resp, err
	} else {
		resp = base.WithdrawRes{
			OrderSn:      req["Order"].(map[string]any)["OrderNo"].(string),
			ThirdOrderSn: draw.SerialId,
		}
		return resp, err
	}
}
